#include "stdafx.h"
#include "JxCtrlBase.h"
#include "JxButton.h"

BEGIN_MESSAGE_MAP(JxButton, JxCtrlBase)
	ON_WM_PAINT()
	ON_WM_MOUSEMOVE()
	ON_WM_TIMER()
END_MESSAGE_MAP()

JxButton::JxButton() 
	: m_bMouseIn(false)
	, m_nImgWidth(0)
	, m_pBMP(NULL)
{
}

JxButton::JxButton(LPCTSTR imgFile)
	: m_bMouseIn(false)
	, m_nImgWidth(0)
{
	m_pBMP = Bitmap::FromFile(imgFile);
	m_nImgWidth = m_pBMP->GetWidth()/3;
}

JxButton::~JxButton()
{
	SafeDelete(m_pBMP);
}

/*
void JxButton::PainParent()
{
	CRect	rect;
	GetWindowRect(&rect);
	GetParent()->ScreenToClient(&rect);
	GetParent()->InvalidateRect(&rect);
}*/


void JxButton::OnPaint()
{
	CPaintDC dc(this);
	CRect r;
	GetClientRect(&r);
	if (m_pBMP != NULL)
	{
		HDC memHDC = CreateCompatibleDC(dc.GetSafeHdc());
		Graphics g(memHDC);
		if (m_bMouseIn)
		{
			g.DrawImage(m_pBMP, 0,0,0,0,r.Width(), r.Height(), UnitPixel);
		}
		else
			g.DrawImage(m_pBMP, 0,0,m_nImgWidth,0,r.Width(),r.Height(),UnitPixel);

		BitBlt(dc.GetSafeHdc(), 0,0,r.Width(),r.Height(),memHDC,0,0,SRCCOPY);
		SafeDelete(memHDC);
	}
}

void JxButton::OnMouseMove( UINT nFlags, CPoint point )
{
	if (!m_bMouseIn)
	{
		m_bMouseIn = true;
		Invalidate(TRUE);
		//PainParent();
		SetTimer(1, 50, NULL);
	}
}

void JxButton::OnTimer(UINT_PTR nIDEvent)
{
	CRect r;
	GetClientRect(&r);
	CPoint pt;
	GetCursorPos(&pt);
	ScreenToClient(&pt);
	if (!r.PtInRect(pt))
	{
		m_bMouseIn = false;
		Invalidate(TRUE);
		//PainParent();
		KillTimer(1);
	}
}

void JxButton::SetImage( LPCTSTR imgFile )
{
	SafeDelete(m_pBMP);
	m_pBMP = Bitmap::FromFile(imgFile);
	m_nImgWidth = m_pBMP->GetWidth()/3;
	Invalidate(TRUE);
	//PainParent();
}
